"nodejs";
let currentOcrResult = false;
const engines = require("engines");
const { requestScreenCapture } = require("media_projection");
const { showToast } = require("toast");
console.log(process.versions);

showToast("Hello, Auto.js Pro with Node.js!");

// 从参数中取出Rhino引擎的ID
const serverEngineId = engines.myEngine().execArgv.serverEngineId;
// 根据ID找出Rhino引擎
const serverEngine = engines.getRunningEngines().find((e) => e.id === serverEngineId);

if (!serverEngine) {
  console.error('请运行文件"main.js"，而不是直接启动本代码');
  return;
}

const Koa = require("koa"); // 引入koa

const Router = require("koa-router"); // 引入koa-router
const koaBody = require("koa-body");
const app = new Koa(); // 创建koa应用
const router = new Router(); // 创建路由，支持传递参数

app.use(
  koaBody({
    multipart: true, // 允许上传多个文件
    jsonLimit: 5 * 1024 * 1024, // 文件上传大小
  })
);

function waitOcrResult(params) {
  return new Promise(function (resolve, reject) {
    let setTimeoutId = setTimeout(function () {
      console.log("执行完成 setTimeout");
      resolve(currentOcrResult);
    }, 8000);

    let setIntervalId = setInterval(function () {
      if (currentOcrResult) {
        clearTimeout(setTimeoutId);
        console.log("执行完成 setInterval");
        resolve(currentOcrResult);
        clearInterval(setIntervalId);
        console.log("clearInterval(setIntervalId);");
      }
    }, 30);
  });
}

async function easyedgeOcr(params) {
  console.log("function easyedgeOcr");
  console.log("发送消息 reply");
  console.log("params = " + params);
  currentOcrResult = false;
  serverEngine.emit("reply", params);
  return await waitOcrResult(params);
}

// 监听命令消息
engines.myEngine().on("ocrResult", (ocrResult) => {
  console.log("接收到消息 ocrResult");
  console.log("ocrResult = " + ocrResult);
  currentOcrResult = ocrResult;
});

async function ocr(ctx) {
  console.log("function ocr");
  let imgPath = ctx.request.body.imgPath;
  if (!imgPath) {
    console.log("没有参数: imgPath");
    return {
      info: "请上传参数imgPath",
    };
  }
  const params = {
    action: "ocr",
    imgPath: imgPath,
  };
  let data = await easyedgeOcr(params);
  // let data ={
  //   result:'ocr'
  // }
  ctx.type = "json";
  ctx.body = data;
}
async function captureScreenOCR(ctx) {
  console.log("function captureScreenOCR");
  let rect = ctx.request.body.rect;
  const params = {
    action: "captureScreenOCR",
    rect: rect,
  };
  let data = await easyedgeOcr(params);
  // let data ={
  //   result:'captureScreenOCR'
  // }
  ctx.type = "json";
  ctx.body = data;
}
const actionMappings = {
  ocr: ocr,
  captureScreenOCR: captureScreenOCR,
};
router
  .get("/", async (ctx) => {
    console.log("get /");
    ctx.type = "html";
    ctx.body = "<h1>hello world!</h1>";
  })
  .get("/exit", async (ctx) => {
    console.log("get /exit");
    ctx.type = "html";
    ctx.body = "<h1>exit!</h1>";
    setTimeout(function () {
      console.error("接收到exit请求, 主动停止进程");
      process.kill(process.pid, "SIGTERM");
      // console.log("程序停止");
      // server.close();
      // throw new Error("exit exit exit");
    }, 200);
  })
  .post("/", async (ctx) => {
    console.log("post /");
    let action = ctx.request.body.action;
    console.log(`action = ${action}`);
    console.log("action = " + action);
    console.log("actionMappings[" + action + "] = " + actionMappings[action]);
    if (!action || !actionMappings[action]) {
      ctx.type = "html";
      ctx.body = "<h1>unknown action!</h1>";
      return false;
    }
    return await actionMappings[action](ctx);
  });

app.use(router.routes());
app.use(
  router.allowedMethods({
    throw: true, // 抛出错误，代替设置响应头状态
    notImplemented: () => "不支持当前请求所需要的功能",
    methodNotAllowed: () => "不支持的请求方式",
  })
);
// 启动服务监听本地端口
let port = "34567";
app.listen(port, () => {
  console.log("应用已经启动，http://127.0.0.1:" + port);
});
